"""
系统健康检查管理命令
"""
from django.core.management.base import BaseCommand
from django.db import connection
from django.core.cache import cache
from django.conf import settings
import sys


class Command(BaseCommand):
    help = '检查系统健康状态'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write(self.style.SUCCESS('系统健康检查'))
        self.stdout.write(self.style.SUCCESS('=' * 60))
        self.stdout.write('')

        all_ok = True

        # 1. 检查数据库连接
        self.stdout.write('[1/5] 检查数据库连接...')
        try:
            connection.ensure_connection()
            self.stdout.write(self.style.SUCCESS('  ✓ 数据库连接正常'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'  ✗ 数据库连接失败: {str(e)}'))
            all_ok = False
        self.stdout.write('')

        # 2. 检查Redis连接
        self.stdout.write('[2/5] 检查Redis连接...')
        try:
            test_key = 'health_check_test'
            cache.set(test_key, 'test', 10)
            result = cache.get(test_key)
            if result == 'test':
                self.stdout.write(self.style.SUCCESS('  ✓ Redis连接正常'))
            else:
                self.stdout.write(self.style.WARNING('  ⚠ Redis连接异常'))
                all_ok = False
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'  ✗ Redis连接失败: {str(e)}'))
            all_ok = False
        self.stdout.write('')

        # 3. 检查Celery配置
        self.stdout.write('[3/5] 检查Celery配置...')
        try:
            if hasattr(settings, 'CELERY_AVAILABLE') and settings.CELERY_AVAILABLE:
                self.stdout.write(self.style.SUCCESS('  ✓ Celery已配置'))
                self.stdout.write(f'    Broker: {settings.CELERY_BROKER_URL}')
                self.stdout.write(f'    Backend: {settings.CELERY_RESULT_BACKEND}')
            else:
                self.stdout.write(self.style.WARNING('  ⚠ Celery未安装或未配置'))
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'  ⚠ Celery检查失败: {str(e)}'))
        self.stdout.write('')

        # 4. 检查高德地图API配置
        self.stdout.write('[4/5] 检查高德地图API配置...')
        try:
            amap_config = getattr(settings, 'AMAP_CONFIG', {})
            api_key = amap_config.get('API_KEY', '')
            if api_key:
                self.stdout.write(self.style.SUCCESS('  ✓ 高德地图API Key已配置'))
            else:
                self.stdout.write(self.style.WARNING('  ⚠ 高德地图API Key未配置'))
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'  ⚠ 高德地图API检查失败: {str(e)}'))
        self.stdout.write('')

        # 5. 检查关键设置
        self.stdout.write('[5/5] 检查关键设置...')
        try:
            if settings.DEBUG:
                self.stdout.write(self.style.WARNING('  ⚠ DEBUG模式已启用（生产环境应关闭）'))
            else:
                self.stdout.write(self.style.SUCCESS('  ✓ DEBUG模式已关闭'))

            if settings.SECRET_KEY == 'django-insecure-change-this-in-production':
                self.stdout.write(self.style.WARNING('  ⚠ 使用默认SECRET_KEY（生产环境应修改）'))
            else:
                self.stdout.write(self.style.SUCCESS('  ✓ SECRET_KEY已配置'))

            allowed_hosts = getattr(settings, 'ALLOWED_HOSTS', [])
            if not allowed_hosts or '*' in allowed_hosts:
                self.stdout.write(self.style.WARNING('  ⚠ ALLOWED_HOSTS配置不安全'))
            else:
                self.stdout.write(self.style.SUCCESS('  ✓ ALLOWED_HOSTS已配置'))
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'  ⚠ 设置检查失败: {str(e)}'))
        self.stdout.write('')

        # 总结
        self.stdout.write('=' * 60)
        if all_ok:
            self.stdout.write(self.style.SUCCESS('系统健康检查通过！'))
        else:
            self.stdout.write(self.style.ERROR('系统健康检查发现问题，请修复后重试！'))
            sys.exit(1)
        self.stdout.write('=' * 60)

